// Header
window.HeaderView = Backbone.View.extend({
	initialize: function() {
		//setting the template
		this.template = _.template( tpl.get('header') );
	},
	
	render: function() {
		$(this.$el).html( this.template() );
		
		return this.el;
	},
	
	events: {
		"click .new": "newWine"
	},
	
	newWine: function() {
		App.navigate( 'wines/new', true );
		
		return false;
	}
});

// Start
window.StartView = Backbone.View.extend({
	initialize: function() {
		//setting the template
		this.template = _.template( tpl.get('start') );
	},
	
	render: function() {
		$(this.$el).html( this.template() );
		
		return this.el;
	}
});

// wine-details
window.WineView = Backbone.View.extend({
	initialize: function() {
		this.template = _.template( tpl.get('wine-details') );
		
		this.model.bind( "change", this.render, this);
	},
	
	render: function() {
		$(this.$el).html( this.template( this.model.toJSON() ) );
		
		return this.el;
	},
	
	events: {
		"click .save": "saveWine",
		"click .delete": "deleteWine"
	},
	
	saveWine: function() {
		this.model.set({
			name: $('#name').val(),
			grapes: $('#grapes').val(),
			country: $('#country').val(),
			region: $('#region').val(),
			year: $('#year').val(),
			description: $('#description').val()
		});
		
		if ( this.model.isNew() ) {
			var self = this;
			
			app.wineList.create( this.model, {
				success: function() {
					app.navigate( "wines/" + self.model.id, false);
				}
			});
		} else {
			this.model.save();
		}
		
		return false;
	},
	
	deleteWine: function() {
		this.model.destroy({
			sucess: function() {
				alert("Wine was deleted successfully");
				window.history.back();
			}
		});
		
		return false;
	}
});

// Wine-list
window.WineListView = Backbone.View.extend({
	tagName: 'ul',
	
	initialize: function() {
		var self = this;
		
		this.model.bind( "reset", this.render, this );
		this.model.bind( "add", function( wine ) {
			$(self.el).append( new WineListItemView({
				model: wine
			}).render())
		});
	},
	
	render: function() {
		_.each( this.model.models, function( wine ) {
			$(this.el).append( new WineListItemView({
				model: wine
			}).render())
		}, this);
		
		return this.el;
	}
});

window.WineListItemView = Backbone.View.extend({
	tagName: 'li',
	
	initialize: function() {
		this.template = _.template( tpl.get('wine-list') );
		
		this.model.bind( "change", this.render(), this);
		this.model.bind( "destroy", this.close(), this);
	},
	
	render: function() {
		$(this.$el).html( this.template( this.model.toJSON() ) );
		
		return this.el;
	}
});